package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tbit.uqbike.object.pojo.RefundOrder;
import com.tbit.uqbike.object.pojo.TransactionOrderQuery;
import com.tbit.uqbike.object.pojo.dto.TransactionOrderIncomeDTO;
import com.tbit.uqbike.object.pojo.dto.TransactionOrderIncomeDownloadDTO;
import com.tbit.uqbike.object.pojo.dto.TransactionOrderIncomePageDTO;
import com.tbit.uqbike.object.pojo.vo.TransactionOrderIncomeVO;
import com.tbit.uqbike.object.pojo.vo.TransactionOrderTotalIncomeVO;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.service.business.RefundOrderService;
import com.tbit.uqbike.service.business.TransactionOrderStatService;
import com.tbit.uqbike.webmanager.dao.log.TransactionLogDao;
import com.tbit.uqbike.webmanager.util.BeanUtils;
import com.tbit.uqbike.webmanager.util.StringUtil;
import com.tbit.uqbike.webmanager.util.csv.CsvExportUtils;
import com.tbit.uqbike.webmanager.util.csv.entity.CsvBaseEntity;
import com.tbit.uqbike.webmanager.util.csv.entity.ExportHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 商品交易订单serviceImpl
 *
 * @AUTHOR: wei.xing
 * @DATE: 2022-11-22 17:20
 **/
@Service
public class TransactionOrderStatServiceImpl implements TransactionOrderStatService {

    @Autowired
    TransactionLogDao transactionLogDao;

    @Autowired
    CsvExportUtils csvExportUtils;
    @Resource
    private RefundOrderService refundOrderService;

    @Override
    public TransactionOrderTotalIncomeVO getTotalIncome(TransactionOrderIncomeDTO dto) {
        TransactionOrderQuery query = BeanUtils.copyProperties(dto, TransactionOrderQuery.class);
        query.setAccountIds(StringUtil.getIntegerList(dto.getAccountIds()));
        return transactionLogDao.getTransactionOrderTotalIncome(query);
    }

    @Override
    public PageResult<TransactionOrderIncomeVO>
    getIncomePage(TransactionOrderIncomePageDTO dto) {
        TransactionOrderQuery query = BeanUtils.copyProperties(dto, TransactionOrderQuery.class);
        query.setAccountIds(StringUtil.getIntegerList(dto.getAccountIds()));
        //分页查询
        PageHelper.startPage(dto.getPageNO(), dto.getRowCount());
        List<TransactionOrderIncomeVO> list = transactionLogDao.getTransactionOrderIncomeList(query);
        //查询退款状态
        List<String> orderNoList = list.stream().map(TransactionOrderIncomeVO::getBusinessNO).collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(orderNoList)){
            List<RefundOrder> refundOrders = refundOrderService.getByBusinessNoList(orderNoList);
            Map<String, List<RefundOrder>> map = refundOrders.stream().collect(Collectors.groupingBy(RefundOrder::getBusinessNO));
            for (TransactionOrderIncomeVO vo : list) {
                List<RefundOrder> refundOrders1 = map.get(vo.getBusinessNO());
                if (CollectionUtil.isEmpty(refundOrders1)){
                    continue;
                }
                // 过滤出退款中状态
                Integer refundStatus = refundOrders1.stream()
                        .filter(order -> order.getRefundStatus() == 0)
                        .findFirst()
                        .map(order -> 0)
                        .orElse(null);
                vo.setRefundStatus(refundStatus);
            }
        }

        PageInfo<TransactionOrderIncomeVO> pageInfo = new PageInfo(list);
        return new PageResult<>(dto.getPageNO(), dto.getRowCount(), pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getList());
    }

    @Override
    public String exportIncome(TransactionOrderIncomeDownloadDTO downloadDTO) {
        //获取临时文件路径
        File tempFile = csvExportUtils.getTempFile();
        try {
            File file = exportIncome(downloadDTO, tempFile);
            String uploadFileName = UUID.randomUUID().toString().replaceAll("-", "");
            //压缩文件，并上传oss
            return csvExportUtils.uploadZip(tempFile, uploadFileName, file);
        } finally {
            //删除本地文件
            FileUtil.del(tempFile);
        }
    }

    @Override
    public File exportIncome(TransactionOrderIncomeDownloadDTO downloadDTO, File tempFile) {
        //自定义导出的处理器
        ExportHandler exportHandler = new ExportHandler() {
            @Override
            public List handle(CsvBaseEntity baseEntity) {
                TransactionOrderQuery query = BeanUtils.copyProperties(downloadDTO, TransactionOrderQuery.class);
                query.setAccountIds(StringUtil.getIntegerList(downloadDTO.getAccountIds()));
                query.setStartTime(baseEntity.getStartTime());
                query.setEndTime(baseEntity.getEndTime());
                List<TransactionOrderIncomeVO> list = transactionLogDao.getTransactionOrderIncomeList(query);
                return list;
            }
        };

        Date startTime = downloadDTO.getStartTime();
        Date endTime = downloadDTO.getEndTime();
        //多线程导出csv文件
        return csvExportUtils.exportBigCsv(exportHandler, TransactionOrderIncomeVO.class, startTime, endTime, tempFile, downloadDTO.getFileName());
    }
}
